package org.jgs1904.work.controller;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Scanner;

import org.jgs1904.work.entity.Message;
import org.jgs1904.work.entity.Users;
import org.jgs1904.work.service.MessageService;

/**
 * 留言控制器
 * @author dyf
 * @date 2020年2月4日
 */
public class MessageController {
	private Scanner sc = new Scanner(System.in);
	private MessageService messageService = new MessageService();
	private Users users;
	
	public void hello(Users onlineUser) {
		users = onlineUser;
		
		System.out.println("请选择：1.查看留言板  2.给他人留言");
		int choose = sc.nextInt();
		switch (choose) {
		case 1:
			showMyMessage();
			break;
		case 2:
			sendMessage();
			break;
		default:
			System.out.println("选择错误！");
			break;
		}
	}

	// 给他人留言
	private void sendMessage() {
		System.out.println("请输入对方用户名：");
		String targetUsername = sc.next();
		System.out.println("请输入留言内容：");
		String content = sc.next();
		
		int result = 0;
		try {
			result = messageService.sendMessage(Message.builder().author_id(users.getId()).content(content).target_username(targetUsername).build());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		if (result != 0) {
			System.out.println("留言成功！");
		} else {
			System.out.println("留言失败！");
		}
		
	}

	// 查看我的留言板
	private void showMyMessage() {
		System.out.println("留言板内容：");
		
		List<Message> messages = null;
		try {
			messages = messageService.getMyMessage(users.getId());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		if (messages != null) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
			for (int i = 0; i < messages.size(); i++) {
				Message message = messages.get(i);
				System.out.println(i + 1 + "." + message.getContent() + "[作者：" + message.getAuthor_name() + " -- 时间：" + sdf.format(message.getCreate_time()) + "]");
			}
		} else {
			System.out.println("暂无留言！");
		}
		
	}
	
}
